package com.shanzmoo.base.util;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 异常工具类
 * @author Gzhao 2020/12/25
 */
public class SExceprtionUtils {

    /**
     * 获取参数校验异常信息
     * @param exception
     * @return
     */
    public static String obtainMethodArgumentNotValidExceptionErrorMsg(MethodArgumentNotValidException exception) {
        Set<String> errorMsgSet = new HashSet<>();
        try {
            //获取校验的信息
            List<FieldError> bindingResult = exception.getBindingResult().getFieldErrors();
            for (FieldError fieldError : bindingResult) {
                errorMsgSet.add(fieldError.getDefaultMessage());
            }
        } catch (Exception e1) {
            errorMsgSet.add("系统异常");
        }
        StringBuilder errorMsg = new StringBuilder();
        Iterator<String> iterator = errorMsgSet.iterator();
        while(iterator.hasNext()){
            errorMsg.append(iterator.next() + ";");
        }
        return errorMsg.toString();
    }
}
